package com.treetao.union.web.controller.system;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.treetao.union.core.redis.RedisService;
import com.treetao.union.db.model.vo.LayerData;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.web.constant.Constants;
import com.treetao.union.web.controller.BaseAdminController;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/system/redis")
public class SysRedisController extends BaseAdminController {
	@Autowired
	private RedisService redisService;

	@PostMapping("delete")
	@ResponseBody
	public RestResponse delete(@RequestParam(value = "key", required = true) String key) {
		long count = redisService.del(key);
		if(count==0) {
			return RestResponse.failure("删除失败："+count);
		}
		return RestResponse.success();
	}

	@GetMapping("list")
	public String list() {
		return "admin/system/redis/list";
	}

	@PostMapping("list")
	@ResponseBody
	public LayerData<Map<String, Object>> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, ServletRequest request) {
		Map map = WebUtils.getParametersStartingWith(request, "s_");
		String patternKey = "*";
		String key = (String) map.get("key");
		if(StringUtils.isNotEmpty(key)) {
			patternKey = key;
		}
		LayerData<Map<String, Object>> layerData = new LayerData<>();
		
		List<Map<String, Object>> keys = redisService.findKeysForPage(patternKey, page, limit);
		
		layerData.setData(keys);
		return layerData;
	}
}
